package com.smitish.vueblog.controller;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smitish.vueblog.common.lang.Result;
import com.smitish.vueblog.entity.Blog;
import com.smitish.vueblog.entity.Comment;
import com.smitish.vueblog.entity.Logs;
import com.smitish.vueblog.mapper.CommentMapper;
import com.smitish.vueblog.service.BlogService;
import com.smitish.vueblog.service.CommentService;
import com.smitish.vueblog.service.LogsService;
import com.smitish.vueblog.service.UserService;
import com.smitish.vueblog.util.ShiroUtil;
import com.smitish.vueblog.vo.CommentUserVO;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Smitish
 * @since 2020-12-02
 */
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    CommentService commentService;


    @Autowired
    UserService userService;

    @Autowired
    BlogService blogService;


    @Autowired
    LogsService logsService;

    /**
     * 某一个用户所评论的全部条数
     *
     * @param id 用户ID
     * @return 返回一个集合
     */
    @GetMapping("/get/{id}")
    public Result getAll(@PathVariable(name = "id") Long id) {
        List<Comment> created = commentService.list(new QueryWrapper<Comment>()
                .orderByDesc("created")
                .eq("user_id", id));
        return Result.success(created);
    }


    /**
     * 查询某篇文章的所有评论数量以及数量集
     *
     * @param id 文章id
     * @return 返回评论数量 和 结果集合
     */
    @GetMapping("/getPost/{id}")
    public Map<String, Object> getPostComment(@PathVariable(name = "id") Long id) {
        HashMap<String, Object> map = new HashMap<>();
        int count = commentService.count(new QueryWrapper<Comment>()
                .orderByDesc("created")
                .eq("post_id", id));
        if (count != 0) {
            List<Comment> list = commentService.list((new QueryWrapper<Comment>()
                    .orderByDesc("created")
                    .eq("post_id", id)));
            map.put("code", 200);
            map.put("msg", "查询成功");
            map.put("count", count);
            map.put("data", list);
        } else {
            map.put("code", 400);
            map.put("msg", "没有评论");
        }
        return map;
    }


    /**
     * 需要进行Token身份验证的评论
     *
     * @param comment 评论的实体类
     * @return 返回状态码
     */
    @RequiresAuthentication
    @PostMapping("/post")
    public Result postComment(@Validated @RequestBody Comment comment) {
        // 防止恶意post提交不属于自己的评论
        Assert.isTrue(comment.getUserId().equals(ShiroUtil.getProfile().getId().toString()), "没有权限提交评论");
        boolean b = commentService.saveOrUpdate(comment);
        Logs logs = new Logs();
        logs.setUserId(ShiroUtil.getProfile().getId());
        if (b) {
            // 查询m_blog表中的博客标题
            Blog blogServiceById = blogService.getById(comment.getPostId());
            logs.setLogContent("评论了\"" + blogServiceById.getTitle() + "\"");
            logsService.saveOrUpdate(logs);
            return Result.succ(200, "评论成功", null);
        }
        return Result.fail("评论失败");
    }


    /**
     * 通过文字ID 分页评论
     *
     * @param id          文章ID
     * @param currentPage 当前页
     * @return 返回结果集
     */
    @GetMapping("/getPageComment/{id}")
    public Result getPageComment(@PathVariable(name = "id") Long id, @RequestParam(defaultValue = "1") Integer currentPage) {
        // 设置每一页 评论的数量
        Page page = new Page(currentPage, 5);
        // 分页查询
        IPage iPage = commentService.page(page, new QueryWrapper<Comment>()
                .orderByDesc("created")
                .eq("post_id", id));
        // 返回结果集
        return Result.success(iPage);
    }


    /**
     * 多表连接的文章评论查询
     * 多表连接为了查询到用户的头像
     *
     * @param id          文章id
     * @param currentPage 评论当前页码
     * @return 返回的文章评论信息
     */
    @GetMapping("/getPage/{id}")
    public Result lists(@PathVariable(name = "id") Long id, @RequestParam(defaultValue = "1") Integer currentPage) {
        Page<CommentUserVO> commentUser = commentService.getCommentUser(new Page<>(currentPage, 5), id);
        return Result.success(commentUser);
    }

}
